<template>
  <PageContainer>
    <Header title="圈子设置" />
    <view class="hb-p-3">
      <!-- 基础资料 -->
      <view class="hb-bg-white hb-rounded-xl hb-box-shadow-base hb-mb-3">
        <view class="hb-py-3 hb-px-4 hb-border-b hb-border-solid hb-border-[#EBEDF0]">
          <TmCell
            _class="hb-font-bold"
            title="基础资料"
            :label-font-size="32"
            :transparent="true"
            :margin="[0, 0]"
            :padding="[0, 0]"
          >
            <template #right>
              <TmButton
                icon="ali-icon icon-edit"
                _class="hb-font-normal"
                :margin="[0, 0]"
                :padding="[20, 0]"
                :block="true"
                :follow-theme="false"
                color="primary"
                :height="48"
                :font-size="24"
                :round="16"
                label="编辑"
                @click="handleEditCircleInfo"
              />
            </template>
          </TmCell>
        </view>
        <TmCell
          _class="hb-font-bold"
          title="圈子头像"
          :label-font-size="32"
          :transparent="true"
          :margin="[0, 0]"
          :padding="[32, 24]"
        >
          <template #right>
            <TmImage
              :src="data?.avatar"
              :width="56"
              :height="56"
              :round="4"
              error-img-type="unit"
            />
          </template>
        </TmCell>
        <TmCell
          _class="hb-font-bold"
          title="圈子名称"
          :label-font-size="32"
          :transparent="true"
          :margin="[0, 0]"
          :padding="[32, 24]"
        >
          <template #right>
            <TmText _class="hb-font-normal" :label="data?.name" :font-size="28" />
          </template>
        </TmCell>
        <TmCell
          _class="hb-font-bold"
          title="圈子简介"
          :label-font-size="32"
          :transparent="true"
          :margin="[0, 0]"
          :padding="[32, 24, 32, 16]"
          :right-icon="''"
        />
        <view class="hb-px-4 hb-pb-3">
          <TmText
            _class="text-overflow-3"
            :label="data?.description"
            :font-size="28"
            color="#646566"
          />
        </view>
      </view>
      <!-- 二维码 -->
      <view class="hb-bg-white hb-rounded-xl hb-box-shadow-base hb-mb-3">
        <TmCell
          _class="hb-font-bold"
          title="圈子二维码"
          :label-font-size="32"
          :transparent="true"
          :margin="[0, 0]"
          :padding="[32, 24]"
          @click="handleShareQrCode"
        >
          <template #right>
            <view class="hb-flex hb-items-center">
              <TmIcon
                _class="hb-font-normal"
                name="ali-icon icon-piaozhongerweima"
                color="#969799"
                :font-size="48"
              />
              <TmIcon
                _class="hb-ml-1 hb-font-normal"
                name="tmicon-angle-right"
                color="#969799"
                :font-size="24"
              />
            </view>
          </template>
        </TmCell>
      </view>
      <!-- 权限 -->
      <view class="hb-bg-white hb-rounded-xl hb-box-shadow-base">
        <view class="hb-px-4 hb-py-3 hb-flex hb-items-center hb-justify-between">
          <view class="hb-flex-1 hb-mr-4">
            <TmText _class="hb-font-bold hb-mb-1" label="加入圈子审核" :font-size="32" />
            <TmText
              label="开启后，申请加入圈子需要管理员确认"
              :font-size="24"
              color="#999996"
            />
          </view>
          <TmSwitch
            v-model="joinAuditEnabled"
            text
            barIcon=""
            :load="switchLoading"
            @change="handleJoinAuditEnabledChange"
          />
        </view>
        <TmCell
          v-if="isSuperAdmin"
          _class="hb-font-bold"
          title="圈子管理员"
          :label-font-size="32"
          :transparent="true"
          :margin="[0, 0]"
          :padding="[32, 24]"
          @click="handleCircleAdminManagement"
        >
          <template #right>
            <view class="hb-flex hb-items-center">
              <TmText
                _class="hb-font-normal"
                :label="`${data?.adminNum || 0} 位`"
                color="#969799"
                :font-size="28"
              />
              <TmIcon
                _class="hb-ml-1 hb-font-normal"
                name="tmicon-angle-right"
                color="#969799"
                :font-size="24"
              />
            </view>
          </template>
        </TmCell>
        <TmCell
          v-if="isSuperAdmin"
          _class="hb-font-bold"
          title="转移超级管理员"
          :label-font-size="32"
          :transparent="true"
          :margin="[0, 0]"
          :padding="[32, 24]"
          @click="handleTransferSuperAdmin"
        >
          <template #right>
            <view class="hb-flex hb-items-center">
              <TmIcon
                _class="hb-ml-1 hb-font-normal"
                name="tmicon-angle-right"
                color="#969799"
                :font-size="24"
              />
            </view>
          </template>
        </TmCell>
        <TmCell
          _class="hb-font-bold"
          title="谁可以上传共享文件？"
          :label-font-size="32"
          :transparent="true"
          :margin="[0, 0]"
          :padding="[32, 24]"
          @click="handleCircleFileUploadLimit"
        >
          <template #right>
            <view class="hb-flex hb-items-center">
              <TmText
                _class="hb-font-normal"
                :label="getFileUploadPolicyText"
                color="#969799"
                :font-size="28"
              />
              <TmIcon
                _class="hb-ml-1 hb-font-normal"
                name="tmicon-angle-right"
                color="#969799"
                :font-size="24"
              />
            </view>
          </template>
        </TmCell>
      </view>

      <BottomSubmit
        v-if="isSuperAdmin"
        submit-btn-label="解散圈子"
        submit-btn-color="#EA5E0E"
        @submit="handleDissolveCircle"
      />
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  /* circleSetting 圈子设置 */
  import { circleSettingDetail, dissolveCircle, updateCircleInfo } from '@/api/contact';
  import { CircleDetailResult } from '@/api/contact/types';
  import { RoleTypeEnum } from '@/enums/LoginEnum';
  import { TabbarPageEnum } from '@/enums/PageEnum';
  import { FileUploadPolicyEnum } from '@/enums/PublicEnum';
  import { useSaveFile } from '@/hooks/file/useSaveFile';
  import { CircleSetting } from '@/router/types/modules';
  import { useUserStore } from '@/store/modules/user';
  import { Toast } from '@/utils';

  let success: CircleSetting['success'];
  const data = ref<CircleDetailResult>();

  const joinAuditEnabled = ref(false);

  customOnload<'circleSetting'>(async (op) => {
    const res = await circleSettingDetail({ uuid: op.uuid });
    joinAuditEnabled.value = !!res.joinAuditEnabled;
    data.value = res;
    success = op.success;
  });

  const isSuperAdmin = computed(() => {
    return data.value?.roleType === RoleTypeEnum.SUPER_ADMIN;
  });

  const getFileUploadPolicyText = computed(() => {
    const fileUploadPolicy = data.value?.fileUploadPolicy;
    switch (fileUploadPolicy) {
      case FileUploadPolicyEnum.ALL_MEMBERS:
        return '所有成员';
      case FileUploadPolicyEnum.ADMINS_ONLY:
        return '仅管理员';
      default:
        return '部分成员';
    }
  });

  const handleEditCircleInfo = () => {
    navigateTo({
      name: 'editCircleInfo',
      options: {
        uuid: data.value!.uuid,
        success: (d) => {
          data.value!.name = d.name;
          data.value!.description = d.description;
          data.value!.avatar = d.avatar;
          success?.('baseInfo');
        },
      },
    });
  };

  const handleShareQrCode = () => {
    useSaveFile()
      .downloadFile(data.value!.qrCodeUrl)
      .then((path) => {
        uni.showShareImageMenu({
          path,
        });
      });
  };

  const switchLoading = ref(false);
  /**
   * @description 开启加入圈子审核
   * @param {boolean} value
   */
  const handleJoinAuditEnabledChange = (value: boolean) => {
    switchLoading.value = true;
    updateCircleInfo({
      id: data.value!.id,
      joinAuditEnabled: value ? 1 : 0,
    }).finally(() => {
      switchLoading.value = false;
    });
  };

  const handleCircleFileUploadLimit = () => {
    navigateTo({
      name: 'circleFileUploadLimit',
      options: {
        id: data.value!.id,
        fileUploadPolicy: data.value!.fileUploadPolicy,
        success: (d) => {
          data.value!.fileUploadPolicy = d.fileUploadPolicy;
          success?.('baseInfo');
        },
      },
    });
  };

  const handleDissolveCircle = () => {
    uni.showModal({
      title: '解散圈子',
      content:
        '确定要解散圈子吗？圈子解散后，所有成员均无法再进入圈子，圈子内共享的文件也将同步清除！',
      cancelColor: '#999996',
      cancelText: '取消',
      confirmColor: '#EA5E0E',
      confirmText: '确认解散',
      success: async (res) => {
        if (res.confirm) {
          await dissolveCircle({ id: data.value!.id });
          useUserStore().getUserInfo();
          Toast({
            title: '解散成功',
            success: () => switchTab(TabbarPageEnum.BASE_HOME),
          });
        }
      },
    });
  };

  /**
   * @description 转移超级管理员
   */
  const handleTransferSuperAdmin = () => {
    navigateTo({
      name: 'transferSuperAdmin',
      options: {
        id: data.value!.id,
      },
    });
  };

  const handleCircleAdminManagement = () => {
    navigateTo({
      name: 'circleAdminManagement',
      options: {
        id: data.value!.id,
        success: (num) => {
          data.value!.adminNum = num;
          success?.('memberList');
        },
      },
    });
  };
</script>

<style lang="scss" scoped></style>
